package com.ts.api.http.receive.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.entity.ApiParameter;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyHuiXinQianBaoAnXin;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeHuiXinQianBaoAnXin;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * 荟信钱包
 *
 * https://apifox.com/apidoc/shared-fc772035-59bc-468b-8e14-886e15bb1343 api出量 FS9yzwEw
 *
 * @author WJB
 */
@ApiReceive(apiClientId = "1934282718107815936",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5HuiXinQianBaoAnXin implements ApiReceivePhoneMd5ConvertHandler {

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        return null;
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String body = requestVO.getBody();
        return new ApiReceiveDecrypt(body);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeHuiXinQianBaoAnXin parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeHuiXinQianBaoAnXin.class);

        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        apiParameter.put("outRequestNo", parse.getOutRequestNo());

        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        boolean suc = dataExchangeMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", 500);
            resultMap.put("message", dataExchangeMessage.getBizMsg());
            return resultMap;
        }
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        dataExchangeMessage.createUniqueId(apiParameter.get("outRequestNo"));

        //成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", 0);
        resultMap.put("message", "撞库成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  价格元
            dataMap.put("price", dataExchangeMessage.getPrice());
            //  授权链接
            dataMap.put("url", dataExchangeMessage.getCallUrl());
            //  产品logo
            dataMap.put("productLogo", dataExchangeMessage.getLogoPath());
            dataMap.put("logo", dataExchangeMessage.getLogoPath());
            //  机构名称
            dataMap.put("companyName", dataExchangeMessage.getOrgName());
            //  产品名称
            dataMap.put("productName", dataExchangeMessage.getDisplayName());
            //  协议信息
            dataMap.put("agreements", CollUtils.newArrayList(newList -> {
                Map<String, Object> protocol = MapUtils.newLinkedHashMap();
                protocol.put("agreementName", "个人信息授权协议");
                protocol.put("agreementUrl", "https://axh.rongyiudai.com/h5ViewProtocol?uniqueCode=1fc1379861b34ef0898d7864c33b18e2");
                newList.add(protocol);
            }));
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyHuiXinQianBaoAnXin parse = apiReceiveDecrypt.parse(ApiReceiveApplyHuiXinQianBaoAnXin.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        boolean suc = applyMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", 500);
            resultMap.put("message", applyMessage.getBizMsg());
            return resultMap;
        }

        // 成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", 0);
        resultMap.put("message", "申请成功");
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {

        // sex 性别 0:女 1:男
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "1", "0")
                    .when(sex, "0", "1")
                    .end();
            apiUserRequest.setSex(sexChoose);
        }

        //  年龄(21岁-55岁)
        if (ValidParam.isNotEmpty(apiUserRequest.getAge())) {
            String age = ApiDictUtils.convertAge(apiUserRequest.getAge());
            apiUserRequest.setAge(age);
        }

        // monthIncome 月收入 单位元
        // monthlySalary 月收入
        // 1 1000-3000
        // 2 3000-8000
        // 3 8000~15000
        // 4 15000~30000
        // 5 30000以上
        String monthlySalary = apiUserRequest.getMonthlySalary();
        if (ValidParam.isNotEmpty(monthlySalary)) {
            apiUserRequest.setMonthlySalary(ApiDictUtils.convertMonthlySalary(monthlySalary));
        }

        // loanAmt 贷款金额(单位：万元) 最小1 最高20
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            apiUserRequest.setLoanAmount(ApiDictUtils.convertLoanAmount(loanAmount, false));
        }

        // profession 职业 1：上班族 2：公务员/事业单位 3：私营业主（有营业执照） 4：个体户（无营业执照） 5其他
        // career
        //   1	上班族
        //   2	自由职业
        //   3	企业主（有营业执照）
        //   4	公务员或事业单位
        //   5	个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                    .when(career, "1", "1")
                    .when(career, "2", "4")
                    .when(career, "3", "3")
                    .when(career, "4", "5")
                    .when(career, "5", "2")
                    .end();
            apiUserRequest.setCareer(value);
        }

        // fund 公积金 1：无公积金 2：缴纳未满6个月 3：缴纳6个月以上
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "1", "1")
                    .when(providentFund, "2", "2")
                    .when(providentFund, "3", "3")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        // social 社保 1：无社保 2：缴纳未满6个月 3：缴纳6个月以上
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "1", "1")
                    .when(socialSecurity, "2", "2")
                    .when(socialSecurity, "3", "3")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        // house 房产情况 1：无房产 , 2：有房产、不抵押 , 3：有房产、可抵押
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "1", "1")
                    .when(realEstateInfo, "2", "2")
                    .when(realEstateInfo, "3", "3")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        // car 车产情况 1：无车产 , 2：有车产,不抵押 , 3: 有车产、可抵押
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "1", "1")
                    .when(carInfo, "2", "2")
                    .when(carInfo, "3", "3")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        // zhima 芝麻分 1：无芝麻分 2：600分以下 3：600~650分 4：650~700分 5：700分以上
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "2", "1")
                    .when(sesameCredit, "3", "2")
                    .when(sesameCredit, "4", "3")
                    .when(sesameCredit, "5", "4")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // insurance 保单 1：无保险保单 , 2：缴纳未满 1 年 , 3：缴纳 1 年以上
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "1", "1")
                    .when(insurancePolicy, "2", "2")
                    .when(insurancePolicy, "3", "3")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // salaryType 工资发放形式 1：银行卡 2：现金 3：自存
        // salaryPayMethod
        // 1 银行代发打卡
        // 2 现金收入
        // 3 个人转账
        String salaryPayMethod = apiUserRequest.getSalaryPayMethod();
        if (ValidParam.isNotEmpty(salaryPayMethod)) {
            String value = ChooseEq.create()
                    .when(salaryPayMethod, "1", "1")
                    .when(salaryPayMethod, "2", "2")
                    .when(salaryPayMethod, "3", "3")
                    .end();
            apiUserRequest.setSalaryPayMethod(value);
        }

        // workAge 工龄 1：0~6个月 2：6~12个月 3：12个月以上
        // 1 0-6个月
        // 2 6-12个月
        // 3 12个月以上
        String yearsService = apiUserRequest.getYearsService();
        if (ValidParam.isNotEmpty(yearsService)) {
            String value = ChooseEq.create()
                    .when(yearsService, "1", "1")
                    .when(yearsService, "2", "2")
                    .when(yearsService, "3", "3")
                    .end();
            apiUserRequest.setYearsService(value);
        }

        // business 营业执照 1:未注册 , 2:注册 1 年以下 , 3:注册 1-5 年 , 4:注册 5 年以上
        // 营业执照注册年限
        // 1 未注册
        // 2 注册1年以下
        // 3 注册1~5年
        // 4 注册5年以上
        String bizLicenseYear = apiUserRequest.getBizLicenseYear();
        if (ValidParam.isNotEmpty(bizLicenseYear)) {
            String value = ChooseEq.create()
                    .when(bizLicenseYear, "1", "1")
                    .when(bizLicenseYear, "2", "2")
                    .when(bizLicenseYear, "3", "3")
                    .when(bizLicenseYear, "4", "4")
                    .end();
            apiUserRequest.setBizLicenseYear(value);
        }

        // education 学历 1：初中及以下 2：高中或中专 3：大专 4：本科 5：研究生及以上
        // educationAttainment 学历
        // 1 初中及以下
        // 2 中专
        // 3 高中
        // 4 大专
        // 5 本科
        // 6 研究生及以上
        String educationAttainment = apiUserRequest.getEducationAttainment();
        if (ValidParam.isNotEmpty(educationAttainment)) {
            String value = ChooseEq.create()
                    .when(educationAttainment, "1", "1")
                    .when(educationAttainment, "2", "3")
                    .when(educationAttainment, "3", "4")
                    .when(educationAttainment, "4", "5")
                    .when(educationAttainment, "5", "6")
                    .end();
            apiUserRequest.setEducationAttainment(value);
        }

        // creditCard 信用卡 1：无信用卡 2:有信用卡
        // creditLimit 信用卡额度
        // 1 无信用卡
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        // 6 有信用卡
        String creditLimit = apiUserRequest.getCreditLimit();
        if (ValidParam.isNotEmpty(creditLimit)) {
            String value = ChooseEq.create()
                    .when(creditLimit, "1", "1")
                    .when(creditLimit, "2", "6")
                    .end();
            apiUserRequest.setCreditLimit(value);
        }

        // baitiaoHuabei 白条 1无 2、白条0-2000 3、白条2000-5000 4、白条5000以上
        // btLimit 京东白条可用额度
        // 1 无额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        String btLimit = apiUserRequest.getBtLimit();
        if (ValidParam.isNotEmpty(btLimit)) {
            String value = ChooseEq.create()
                    .when(btLimit, "1", "1")
                    .when(btLimit, "2", "2")
                    .when(btLimit, "3", "3")
                    .when(btLimit, "4", "3")
                    .end();
            apiUserRequest.setBtLimit(value);
        }

        // baitiaoHuabei 花呗 1无 2、花呗0-5000 3、花呗5000-10000 4、花呗10000以上
        // hbLimit 蚂蚁花呗可用额度
        // 1 无额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        apiUserRequest.setHbLimit(apiUserRequest.getBtLimit());
        String hbLimit = apiUserRequest.getHbLimit();
        if (ValidParam.isNotEmpty(hbLimit)) {
            String value = ChooseEq.create()
                    .when(hbLimit, "1", "1")
                    .when(hbLimit, "2", "2")
                    .when(hbLimit, "3", "3")
                    .when(hbLimit, "4", "4")
                    .end();
            apiUserRequest.setHbLimit(value);
        }

        // creditStatus 人行征信情况 1：无人行征信记录 2：人行征信良好无逾期 3：人行征信近2两年有60天以内的逾期
        // 4：人行征信近2两年有60天以上逾期 5：人行征信近两年有90天以上逾期
        // overdue 逾期
        // 1 无逾期
        // 2 当前有逾期
        // 3 一年以内无逾期
        String overdue = apiUserRequest.getOverdue();
        if (ValidParam.isNotEmpty(overdue)) {
            String value = ChooseEq.create()
                    .when(overdue, "1", "1")
                    .when(overdue, "2", "1")
                    .when(overdue, "3", "2")
                    .when(overdue, "4", "2")
                    .when(overdue, "5", "2")
                    .end();
            apiUserRequest.setOverdue(value);
        }

    }


    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return MapUtils.newHashMap(newMap -> {
            newMap.put("outRequestNo", apiReceiveNotice.getDataExchangeId());
        });
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        Integer code = jsonObject.getInteger("code");
        return Eq.object(code, 0);
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return MapUtils.newHashMap(newMap -> {
            newMap.put("outRequestNo", apiReceiveNotice.getDataExchangeId());
        });
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        Integer code = jsonObject.getInteger("code");
        return Eq.object(code, 0);
    }


}
